package com.wuage.application.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuage.application.IUacRoleService;
import com.wuage.domain.mapper.UacRolePermissionMapper;
import com.wuage.domain.model.UacRole;
import com.wuage.domain.model.UacRolePermission;
import com.wuage.application.IUacRolePermissionService;
import com.wuage.infrastructure.status.BizResultCode;
import com.wuage.infrastructure.utils.BeanUtils;
import com.wuage.infrastructure.utils.JwtUtils;
import com.wuage.interfaces.permission.domain.RolePermissionUpdateDO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (UacRolePermission)表服务实现类
 * @Author: makejava
 * @Date: 2021-09-27 17:00:43
 */
@Service("uacRolePermissionService")
public class UacRolePermissionServiceImpl extends ServiceImpl<UacRolePermissionMapper, UacRolePermission> implements IUacRolePermissionService {

    @Resource
    private IUacRoleService roleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRolePermission(List<RolePermissionUpdateDO> rolePermissionUpdateDOS) {
        // 判断当前用户的角色是否拥有这些权限
        // 如果当前用户的角色都没有那些权限。则不能赋予
        UacRole loginUserRole = roleService.getByRoleAndTenant(JwtUtils.getLoginUser().getRole(), JwtUtils.getLoginUser().getTenantId());
        List<UacRolePermission> loginUserRolePermission = this.lambdaQuery().eq(UacRolePermission::getRoleId, loginUserRole.getId()).list();
        if(CollectionUtils.isEmpty(loginUserRolePermission)) {
            throw BizResultCode.ROLE_NOT_HAS_PERMISSION.toException();
        }
        List<Long> loginUserPermissionIds = loginUserRolePermission.stream().map(UacRolePermission::getMenuId).collect(Collectors.toList());
        List<Long> rolePermissionIds = rolePermissionUpdateDOS.stream().map(RolePermissionUpdateDO::getMenuId).collect(Collectors.toList());
        if(!loginUserPermissionIds.containsAll(rolePermissionIds)) {
            throw BizResultCode.ROLE_NOT_HAS_THAT_PERMISSION.toException();
        }

        // 先删除角色的所有旧权限
        this.lambdaUpdate()
                .eq(UacRolePermission::getRoleId, rolePermissionUpdateDOS.get(0).getRoleId())
                .set(UacRolePermission::getDeleted, true)
                .update();

        // 给当前用户赋予新的权限
        List<UacRolePermission> uacRolePermissions = BeanUtils.copyCollections(rolePermissionUpdateDOS, UacRolePermission.class);
        this.saveBatch(uacRolePermissions);
        return true;
    }

    @Override
    public List<UacRolePermission> selectPermission(Long roleId) {
        return this.lambdaQuery().eq(UacRolePermission::getRoleId, roleId).list();
    }
}